package top.codedance.iotp.server.net.tools;

import top.codedance.iotp.server.ServerApplication;
import org.apache.log4j.Logger;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.Security;
import java.util.Properties;

public class MailUtil {
    private static Logger logger = Logger.getLogger(MailUtil.class);
    private Properties properties;
    private Session session;

    public MailUtil(Properties properties) {
        this.properties = properties;
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        Properties p = new Properties();
        p.setProperty("mail.smtp.host", this.properties.getProperty("mail.smtp.host"));
        p.setProperty("mail.smtp.auth", this.properties.getProperty("mail.smtp.auth"));
        p.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        p.setProperty("mail.smtp.socketFactory.fallback", "false");
        p.setProperty("mail.smtp.port", "587");
        p.setProperty("mail.smtp.socketFactory.port", "587");
        session = Session.getDefaultInstance(p, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MailUtil.this.properties.getProperty("mail.smtp.username"), MailUtil.this.properties.getProperty("mail.smtp.password"));
            }
        });
        // 有了这句便可以在发送邮件的过程中在console处显示过程信息，供调试使用（你可以在控制台（console)上看到发送邮件的过程）
        session.setDebug(ServerApplication.commandCli.getArg("logLevel", "ERROR").equals("DEBUG"));
    }

    public void send(final String subject, final String content) {
        ServerApplication.workerPool.submit(() -> {
            MimeMessage message = new MimeMessage(session);
            try {
                // 加载发件人地址
                message.setFrom(new InternetAddress(MailUtil.this.properties.getProperty("mail.from.mail.address")));
                // 加载收件人地址
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(MailUtil.this.properties.getProperty("mail.to.mail.address")));
                // 加载标题
                message.setSubject(subject);
                // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
                Multipart multipart = new MimeMultipart();
                // 设置邮件的文本内容
                BodyPart contentPart = new MimeBodyPart();
                contentPart.setContent(content, "text/html;charset=utf-8");
                multipart.addBodyPart(contentPart);
                message.setContent(multipart);
                message.saveChanges(); // 保存变化
                // 连接服务器的邮箱
                Transport transport = session.getTransport("smtp");
                // 把邮件发送出去
                transport.connect(MailUtil.this.properties.getProperty("mail.smtp.host"), MailUtil.this.properties.getProperty("mail.smtp.username"), MailUtil.this.properties.getProperty("mail.smtp.password"));
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
                logger.debug("Mail send success.");
            } catch (MessagingException e) {
                logger.debug(e.getMessage());
            }
        });
    }
}
